<template>
  <a-modal
    width="60vw"
    title="批量设置价格"
    :visible="visible"
    unmount-on-close
    okText="确认"
    cancel-text="关闭"
    @cancel="close"
    :mask-closable="false"
    :on-before-ok="onSubmit"
    :body-style="{ paddingBottom: '6px' }"
  >
    <page-form :model="form" ref="formRef" layout="vertical" gutter="0" :rules="rules">
      <page-form-row gutter="0">
        <page-form-item field="tenantPriceModelIdList" label="批量设置的车型" size="1">
          <includeAllSelect
            v-model="form.tenantPriceModelIdList"
            :options="tenantPriceModelList"
            :allow-search="{ retainInputValue: true }"
          />
        </page-form-item>
        <page-form-item field="priceTypeList" label="批量设置的价格类型" size="1">
          <a-checkbox-group v-model="form.priceTypeList" @change="onPricetypeChange">
            <a-checkbox :value="item.value" v-for="(item, index) in priceTypeList" :key="index">{{ item.label }}</a-checkbox>
          </a-checkbox-group>
        </page-form-item>
      </page-form-row>
      <!-- 已选中的价格类型 -->
      <div class="price-type-selected-wrapper">
        <div class="price-type-selected-content">
          <template v-for="(item, index) in priceTypeList" :key="index">
            <div
              class="price-type-selected-item"
              :ref="getSelectedRef"
              :value="item.value"
              v-if="form.priceTypeList && form.priceTypeList.includes(item.value)"
            >
              <div class="price-type-selected-item-inner">
                <div class="price-type-selected-item-title">
                  {{ item.label }}
                  <span v-if="item.value == 2">反写时周末价及时间必须填写，且金额需>0，未填写时则反写失败</span>
                </div>
                <div class="price-type-selected-item-content">
                  <!-- 如果是自定义价格和节假日，需要显示自定义时间选择和节假日选择 -->
                  <div class="custom-wrapper" v-if="[4, 5].includes(item.value)">
                    <template v-if="item.value == 4">
                      <page-form-item field="holidayList" label="节假日" size="1">
                        <includeAllSelect v-model="form.holidayList" :options="holidayDictList" labelProp="title" valueProp="prop" />
                      </page-form-item>
                      <a-divider style="margin: 16px 0" />
                      <priceForm :record="form" :priceType="item.prop" />
                    </template>
                    <template v-if="item.value == 5">
                      <!-- 只能选择一个自定义日期 -->
                      <page-form-item field="dateRange" label="自定义日期" size="1">
                        <i-range-picker
                          v-model="form.dateRange"
                          :disabledDate="disabledCustomDate"
                          class="w-full"
                          @change="changeCustomDateFn"
                        />
                      </page-form-item>
                      <a-divider style="margin: 16px 0" />
                      <priceForm :record="form.custPriceList[0]" fieldPrefix="custPriceList.0" :priceType="item.prop" />
                    </template>
                  </div>
                  <template v-else>
                    <priceForm :record="form" :priceType="item.prop" />
                  </template>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </page-form>
  </a-modal>
</template>

<script setup name="BatchPriceSettingModal">
  import { ref, reactive, nextTick, provide } from 'vue'
  import dayjs from 'dayjs'
  import { cloneDeep } from 'lodash-es'
  import { batchSavePrice } from '@/api/business/price.js'
  import priceForm from './price-form.vue'
  import includeAllSelect from '@/components/selector/include-all-select.vue'
  import { Message } from '@arco-design/web-vue'
  import scrollIntoView from 'scroll-into-view-if-needed'
  const emits = defineEmits(['success'])

  // 节假日
  const holidayDictList = [
    { title: '元旦', prop: 'newYearPrice' },
    { title: '春节', prop: 'springPrice' },
    { title: '清明节', prop: 'sweepingDay' },
    { title: '劳动节', prop: 'labourPrice' },
    { title: '端午节', prop: 'dragonBoatPrice' },
    { title: '中秋节', prop: 'midAutumnPrice' },
    { title: '国庆节', prop: 'nationalPrice' },
  ]
  // 批量设置的价格类型 枚举
  const priceTypeList = ref([
    { label: '平日价', value: 1, prop: 'price' },
    { label: '周末价', value: 2, prop: 'weekendPrice' },
    { label: '手续费', value: 3, prop: 'poundageAmount' },
    { label: '节假日价格', value: 4, prop: 'holidayPrice' },
    { label: '自定义价格', value: 5, prop: 'price' },
    { label: '基础保险', value: 6, prop: 'insuranceAmount' },
    { label: '租车押金', value: 7, prop: 'carDeposit' },
    { label: '违章押金', value: 8, prop: 'illegalDeposit' },
  ])
  // 日期禁用逻辑，不能选择今天之前的时间
  const disabledCustomDate = (current) => {
    return dayjs(current).isBefore(dayjs().subtract(1, 'day')) || dayjs(current).isAfter(dayjs().add(120, 'day'))
  }
  // 日期时间变化事件
  const changeCustomDateFn = (val = []) => {
    form.value.custPriceList[0].startTime = val[0]
    form.value.custPriceList[0].endTime = val[1]
  }
  const visible = ref(false)
  const form = ref({})
  // form rules
  const rules = {
    tenantPriceModelIdList: { required: true, message: '请选择批量设置的车型' },
    priceTypeList: { required: true, message: '请选择批量设置的价格类型' },

    holidayList: { required: true, message: '请选择节假日' },
    dateRange: { required: true, message: '请选择自定义日期' },
  }
  // 车型列表
  const tenantPriceModelList = ref([])
  const close = () => {
    visible.value = false
    form.value = {}
  }
  const formRef = ref(null)
  provide('formRef', formRef)

  const selectedRef = reactive({})
  const getSelectedRef = (el) => {
    if (el) {
      const targetValue = el.getAttribute('value') - 0
      selectedRef[targetValue] = el
    }
  }
  // 价格类型 change 事件
  const onPricetypeChange = (val, ev) => {
    const target = ev.target
    const targetValue = target.getAttribute('value') - 0
    // 选中
    if (val.includes(targetValue)) {
      // 选中的时候需要获取对应的 dom 节点
      nextTick(() => {
        scrollIntoView(selectedRef[targetValue], {
          behavior: 'smooth',
          block: 'nearest',
          scrollMode: 'if-needed',
        })
      })
    } else {
      // 取消选中
      console.log('取消选中')
    }
  }
  const buildParam = () => {
    // 处理节假日价格
    const param = cloneDeep(form.value)
    // 选中的价格类型
    const formPriceTypeList = param.priceTypeList
    // 遍历全部的价格类型枚举
    priceTypeList.value.forEach(({ value, prop }) => {
      if (value == 4) {
        // 处理节假日接口传参
        if (formPriceTypeList.includes(4)) {
          const holidayList = param.holidayList
          if (holidayList?.length > 0) {
            holidayList.forEach((item) => {
              // 启程节假日价格
              if (param.holidayPrice) {
                param[item] = param.holidayPrice
              }
              // 渠道节假日价格
              param.channelPriceList.forEach((channelItem) => {
                if (channelItem.holidayPrice) {
                  channelItem[item] = channelItem.holidayPrice
                }
              })
            })
          }
        }
      } else if (value == 5) {
        // 处理自定义价格，未选中时，不传值给接口
        if (!formPriceTypeList.includes(5)) {
          delete param.custPriceList
        }
      } else {
        // 平日价、周末价、手续费、基础保险、违章押金、租车押金
        if (!formPriceTypeList.includes(value)) {
          delete param[prop]
          if (value == 2) delete param.weekendDayList
          param.channelPriceList.forEach((channelItem) => {
            delete channelItem[prop]
            if (value == 2) delete channelItem.weekendDayList
          })
        }
      }
    })
    return param
  }
  const onSubmit = (done) => {
    formRef.value.validate((error) => {
      if (error) {
        done(false)
      } else {
        // 处理价格类型选中又取消选中，更新入参传值
        const param = buildParam()
        batchSavePrice(param)
          .then((res) => {
            Message.success(res.message)
            emits('success')
            close()
            done(true)
          })
          .catch(() => {
            done(false)
          })
      }
    })
  }
  defineExpose({
    open: (id, modelList, channelInfo) => {
      visible.value = true
      form.value.id = id
      form.value.channelPriceList = cloneDeep(channelInfo)
      form.value.custPriceList = [{ channelPriceList: cloneDeep(channelInfo) }]
      form.value.priceTypeList = [1]
      // 车型列表
      tenantPriceModelList.value = modelList
    },
  })
</script>

<style lang="less" scoped>
  .price-type-selected-wrapper {
    overflow-x: hidden;
    min-height: 100px;
    max-height: calc(100vh - 380px);
    overflow-y: auto;
    .price-type-selected-content {
      display: flex;
      flex-wrap: wrap;
      margin-right: -55px;
      .price-type-selected-item {
        margin-right: 55px;
        margin-bottom: 20px;
        flex: 0;
        .price-type-selected-item-inner {
          border: 1px solid #e5e8ef;
          border-radius: 2px 2px 2px 2px;
          .price-type-selected-item-title {
            height: 53px;
            line-height: 53px;
            background: linear-gradient(90deg, #d5e5ff 0%, #ffffff 100%);
            font-weight: 600;
            font-size: 16px;
            color: #1d2129;
            padding-left: 16px;
            span {
              height: 22px;
              font-size: 12px;
              color: #f53f3f;
              font-weight: 400;
              margin-left: 12px;
            }
          }
          .price-type-selected-item-content {
            padding: 16px;
            :deep(.custom-form-item .custom-input-number) {
              width: 248px;
            }
          }
        }
      }
    }
  }
</style>
